package com.coldworks.coldjoke.ui;

import android.widget.ListView;
import com.coldworks.coldjoke.R;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ClickToLoadingMoreListview extends ListView {

	private static final int CLICK_TO_REFRESH = 1;
	private static final int REFRESHING = 2;

	private int mRefreshState;

	private TextView loadingText;
	private ProgressBar loadingProgressBar;
	private OnRefreshOlderListener mOnRefreshOlderListener;

	public ClickToLoadingMoreListview(Context context) {
		super(context);
		setUpViews(context);
	}

	public ClickToLoadingMoreListview(Context context, AttributeSet attrs) {
		super(context, attrs);
		setUpViews(context);
	}

	public ClickToLoadingMoreListview(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
		setUpViews(context);
	}

	private void setUpViews(Context context) {

		// FooterView
		RelativeLayout vLoadingMore = (RelativeLayout) LayoutInflater.from(
				context)
				.inflate(R.layout.navigation_joke_listview_footer, null);
		vLoadingMore.setOnClickListener(new OnClickRefreshOlderListener());
		loadingProgressBar = (ProgressBar) vLoadingMore
				.findViewById(R.id.loading_progressbar);
		loadingText = (TextView) vLoadingMore.findViewById(R.id.loading_text);
		// 加载 Listview 样式
		setCacheColorHint(context.getResources().getColor(R.color.transparent));
		setDividerHeight(5);
		setDivider(null);
		setPadding(10, 0, 10, 0);
		setSelector(R.color.transparent);
		mRefreshState = CLICK_TO_REFRESH;
		addFooterView(vLoadingMore);
	}

	public void setOnRefreshOlderListener(
			OnRefreshOlderListener onRefreshOlderListener) {
		mOnRefreshOlderListener = onRefreshOlderListener;
	}

	private void onRefreshOlder(OnRefreshOlderListener onRefreshListener) {
		onRefreshListener.onRefresh();
	}

	private class OnClickRefreshOlderListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (mRefreshState != REFRESHING) {
				prepareForRefreshOlder();
				onRefreshOlder(mOnRefreshOlderListener);
			}
		}
	}

	public interface OnRefreshOlderListener {
		public void onRefresh();
	}

	private void prepareForRefreshOlder() {
		loadingProgressBar.setVisibility(View.VISIBLE);
		loadingText.setText("正在刷新");
		mRefreshState = REFRESHING;
	}

	public void onRefreshOlderComplete() {
		mRefreshState = CLICK_TO_REFRESH;
		loadingProgressBar.setVisibility(View.GONE);
		loadingText.setText("点击刷新更多");
	}
}
